//
//  AppDelegate.m
//  CarLife
//
//  Created by yu on 2017/6/13.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "AppDelegate.h"
#import "RootManager.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "User.h"
#import "PPNetworkHelper.h"
//#import <AipOcrSdk/AipOcrSdk.h>
#import "LocationManager.h"

#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5
#define kAMapApiKey @"94252bd2be970134e7892f57c393b9f2"

@interface AppDelegate ()<UIAlertViewDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:kScreenBounds];
    self.window.backgroundColor = [UIColor blackColor];
    
    ///<1> 配置高德地图
    [self configureAMapService];
    
    ///<2> IQKeyboardManager
    [self initIQKeyboardManager];
    
    ///<3> 选择根视图控制器
    [RootManager chooseRootVC:self.window];
    
    ///<4> 延时
    // [NSThread sleepForTimeInterval:2.0];
    
    ///<5> 避免滚动视图顶部出现20的空白以及push或者pop的时候页面有一个上移或者下移的异常动画的问题
    [self otherConfig];
    
    ///<5> 开启连续定位
    [self getLocation];
    
    ///<6> Ocr授权
//    [[AipOcrService shardService] authWithAK:@"ABjX4hCikwpHhGabYnG9OypG" andSK:@"Yt2CzPGccdr9MuDFFht1WYUXpHKOHicV"];
    ///<7> 实时检测网络状态
    [self monitorNetworkStatus];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

//+ (AppDelegate* )shareAppDelegate {
//    return (AppDelegate*)[UIApplication sharedApplication].delegate;
//}

#pragma mark - 实时监测网络状态
- (void)monitorNetworkStatus
{
    // 网络状态改变一次, networkStatusWithBlock就会响应一次
    [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {
        switch (networkStatus) {
            case PPNetworkStatusUnknown: break;
            case PPNetworkStatusNotReachable: [MBProgressHUD showToast:@"网络已断开,请检查网络设置"]; break;
            case PPNetworkStatusReachableViaWWAN: break;
            case PPNetworkStatusReachableViaWiFi: break;
            default: break;
        }
    }];
}

- (void)checkForUpdates
{
    [PPNetworkHelper GET:NSStringFormat(@"%@/base/iosVer",kApiPrefix) parameters:nil success:^(id responseObject) {
        NSString *ver = responseObject[@"result"][0][@"verName"];
        PPLog(@"ver = %@",ver);
        NSString *appver = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        //PPLog(@"ver = %@",appver);
        // 存当前版本号
//        [User sharedUser].verson = appver;
        NSInteger verInteger = [[ver stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
        NSInteger appverInteger = [[appver stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
        
        if (appverInteger < verInteger) {
            [[[UIAlertView alloc] initWithTitle:@"应用版本已更新,请更新至新版本" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        }
    } failure:^(NSError *error) {
        PPLog(@"error = %@",error);
    }];
}


//- (BOOL)checkVer:(NSString *)version {
//    NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
//    NSString *app_ver = [info objectForKey:@"CFBundleShortVersionString"];
//    NSArray *versionArray = [version componentsSeparatedByString:@"."];//服务器返回版
//    NSArray *currentVesionArray = [app_ver componentsSeparatedByString:@"."];//当前版本
//    NSInteger a = (versionArray.count >  currentVesionArray.count) ? currentVesionArray.count : versionArray.count;
//
//    for (int i = 0; i< a; i++) {
//        NSInteger a = [[versionArray objectAtIndex:i] integerValue];
//        NSInteger b = [[currentVesionArray objectAtIndex:i] integerValue];
//        if (a > b) {
//            PPLog(@"有新版本");
//            return YES;
//        }else if(a < b){
//            return NO;
//        }
//    }
//    return NO;
//}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/datouzhen/id1323932268?mt=8"]];
    }
}

- (void)configureAMapService {
    [AMapServices sharedServices].apiKey = kAMapApiKey;
    [AMapServices sharedServices].enableHTTPS = YES;
}

- (void)initIQKeyboardManager {
    // 获取类库的单例变量
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    // 控制整个功能是否启用
    keyboardManager.enable = YES;
    // 控制点击背景是否收起键盘
    keyboardManager.shouldResignOnTouchOutside = YES;
    // 控制键盘上的工具条文字颜色是否用户自定义
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES;
    // 有多个输入框时，可以通过点击Toolbar上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews;
    // 控制是否显示键盘上的工具条
    keyboardManager.enableAutoToolbar = YES;
    // 是否显示占位文字
//    keyboardManager.shouldShowTextFieldPlaceholder = YES;
    // 设置占位文字的字体
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17];
    // 输入框距离键盘的距离
    keyboardManager.keyboardDistanceFromTextField = 20.0f;
}

- (void)otherConfig {
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

- (void)getLocation
{
    [LocationManager getLocationInfo:^(double lat, double lng, AMapLocationReGeocode *reGeocode) {
        CLLocation *lo = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
        [[User sharedUser] updateUserLoction:lo reGeocode:reGeocode];
    }];
    
    [LocationManager getChangedAuthStatus:^(CLAuthorizationStatus status) {
        switch (status) {
            case kCLAuthorizationStatusDenied:
            {// 关闭连续定位
                [LocationManager stopUpdatingLocation];
            }
                break;
            case kCLAuthorizationStatusRestricted:
            case kCLAuthorizationStatusNotDetermined:
            case kCLAuthorizationStatusAuthorizedAlways:
            case kCLAuthorizationStatusAuthorizedWhenInUse:
            {// 开始进行连续定位
                [LocationManager startUpdatingLocation];
            }
                break;
            default:
                break;
        }
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
#warning 需要开启！！！！！！！！！！
    ///<0>检查版本，旧版本需强制更新
    [self checkForUpdates];
    
//    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
//    switch (status) {
//        case kCLAuthorizationStatusDenied: PPLog(@"kCLAuthorizationStatusDenied"); break;
//        case kCLAuthorizationStatusRestricted:PPLog(@"kCLAuthorizationStatusRestricted"); break;
//        case kCLAuthorizationStatusNotDetermined:PPLog(@"kCLAuthorizationStatusNotDetermined"); break;
//        case kCLAuthorizationStatusAuthorizedAlways:PPLog(@"kCLAuthorizationStatusAuthorizedAlways"); break;
//        case kCLAuthorizationStatusAuthorizedWhenInUse:PPLog(@"kCLAuthorizationStatusAuthorizedWhenInUse") ;break;
//        default:
//            break;
//    }
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
